import * as THREE from 'three'
import { reactive, ref, watch } from 'vue'

export const useRain = () => {
  const isRaining = ref(false)
  const animationHandle = ref()
  const texture = new THREE.TextureLoader().load("/snowflake1.png")
  console.log('texture: ', texture)
  const spriteMaterial = new THREE.SpriteMaterial({
    map: texture,
  })
  const rainGroup = new THREE.Group()
  for (let i = 0; i < 20000; i++) {
    // 精灵模型共享材质
    const sprite = new THREE.Sprite(spriteMaterial)
    rainGroup.add(sprite)
    sprite.scale.set(10, 10, 10)
    // 设置精灵模型位置，在长方体空间上上随机分布
    // const x = 1000 * (Math.random() - 0.5)
    // const y = 600 * Math.random()
    const z = 1000 * (Math.random() - 0.5)

    const x = window.innerWidth * (Math.random() - 0.5)
    const y = window.innerHeight * Math.random()

    sprite.position.set(x, y,  Math.random() * 1000 - 500)
  }
  console.log('rainGroup: ', rainGroup)
  function loop() {
    // loop()每次执行都会更新雨滴的位置，进而产生动画效果
    rainGroup.children.forEach(sprite => {
      // 雨滴的y坐标每次减1
      sprite.position.y -= 1
      // if (sprite.position.y < 0) {
      //   // 如果雨滴落到地面，重置y，从新下落
      //   sprite.position.y = 600
      // }

      if (sprite.position.y <0) {
        sprite.position.y = window.innerHeight
      }
    })
  }
  const initRain = () => {
    console.log('initRain: ',)
    runRain()
  }




  const runRain = () => {
    isRaining.value = true
    destroyAnimation()
    animate()
  }

  const animate = () => {
    if (isRaining.value) {
      loop()
      animationHandle.value = requestAnimationFrame(animate)
    }
  }
  const destroyAnimation = () => {
    if (animationHandle.value) {
      cancelAnimationFrame(animationHandle.value)
      animationHandle.value = null
    }
  }
  const stopRain = () => {
    isRaining.value = false
    destroyAnimation()
  }

  return {
    initRain,
    runRain,
    stopRain,
    isRaining,
    rainGroup,
  }
}